const _ = require('lodash');
const moment = require('moment');
const Promise = require("bluebird");

/**
 * @api {post} /api/public/v1/withdraw/apply 申请提现
 */
exports.apply = function ({body, user_id}, {models: {Users, UsersWithdraws}, cache: {settings}, redis, config, wechatInstance}) {
    let {amount} = body;
    if (parseFloat(amount) < settings.value('withdraw_limit')) {
        return {success: false, message: '提现金额不能少于' + settings.value('withdraw_limit') + '元'};
    }
    return Users.findOne({where: {id: user_id}}).then(function (user) {
        if (!user.bank_type || !user.bank_name || !user.bank_no) {
            return {success: false, message: '请先设置提现账号'}
        }

        let withdrawRate = settings.value('withdraw_rate_scale') || 0;
        let charge = parseFloat(((amount * withdrawRate) / 100).toFixed(2));
        let data = {
            partner_id: user.partner_id,
            user_id: user.id,
            total_amount: amount,
            charge: charge,
            rate_scale: withdrawRate,
            amount: (amount - charge).toFixed(2),
            bank_type: user.bank_type,
            bank_name: user.bank_name,
            bank_no: user.bank_no,
            bank_tel: user.bank_tel
        }
        /**
         * 创建订单号
         */
        return new Promise(function (resolve) {
            let date = moment().format('YYMMDD');
            let trade_no = 'WD' + date;
            return redis.globalClient.incr(trade_no, function (err, id) {
                if (err) {
                    console.error('\n', err.stack || err.message);
                    return resolve({success: false, message: '创建交易号失败'});
                }
                data.trade_no = trade_no + (id + 1000);
                return resolve({success: true});
            });
        }).then(function () {
            return UsersWithdraws.applyV2(data).then(function (result) {
                if (result.success) {
                    Users.findOne({
                        where: {id: user.partner_id || 1},
                        attrbutes: ['id', 'openid']
                    }).then(function (partner) {
                        if (partner && partner.openid) {
                            let partnerUrl = function () {
                                return config.domain + '/partner_withdraws?id=' + result.data.id;
                            }
                            wechatInstance.shopWebApi.sendText(partner.openid, (user.nickname || user.tel) + '申请提现' + data.amount + '元\n' + moment().format('YYYY-MM-DD HH:mm:ss') + '\n' + partnerUrl(), function (err) {
                                if (err) {
                                    console.error('\n', err.stack || err.message);
                                }
                            });
                        }
                    });
                }
                return result;
            });
        });
    });
}

/**
 * @api {post} /api/public/v1/withdraw/status 更改状态
 */
exports.status = function ({body, user_id}, {models: {UsersWithdraws}}) {
    let {id, status} = body;
    return UsersWithdraws.findOne({where: {id: id, partner_id: user_id}}).then(function (usersWithdraw) {
        if (!usersWithdraw) {
            return {success: false, message: '没有权限'};
        }
        if (status === 'Successful') {
            return UsersWithdraws.successfulV2(id);
        } else if (status === 'Failed') {
            return UsersWithdraws.failedV2(id);
        } else {
            return {success: false};
        }
    });
}